#pragma once
#include<string>
#include"data.hpp"
#include"httplib.h"
#include<Windows.h>


namespace cloud {
	#define SERVER_IP "117.72.11.54"
	#define SERVER_PORT 20000
	class Backup {
	private:
		std::string _back_dir;
		DataMannger* _data;

		std::string GetFileIdentify(const std::string& file_name)
		{
			std::string fidentify;
			Util::FileUtil f(file_name);
			fidentify += f.FilePath();
			fidentify += "-";
			fidentify += std::to_string(f.FileSize());
			fidentify += "-";
			fidentify += std::to_string(f.LastModTime());
			return fidentify;

		}
		bool NeedUpLoad(const std::string& filename)
		{
			Util::FileUtil file(filename);
			std::string old_id = GetFileIdentify(filename);
			std::string id;
			_data->GetOneByKey(file.FilePath(), &id);
			if (old_id == id)
			{
				return false;
			}
			if (time(nullptr) - file.LastModTime() < 5)
			{
				return false;
			}

			return true;
		}
	public:
		Backup(const std::string& back_dir, const std::string& back_file):_back_dir(back_dir)
		{
			_data = new DataMannger(back_file);
		}
		bool Upload(const std::string& filename)
		{
			Util::FileUtil file(filename);
			httplib::Client client(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormDataForClientInput item;
			item.name = "file";
			item.filename = file.FileName();
			file.GetContent(&item.content);
			item.content_type = "application/octet-stream";

			httplib::MultipartFormDataItemsForClientInput items;
			items.push_back(item);
			auto res = client.Post("/upload", items);
			if (!res || res->status != 200)
			{
				return false;
			}
			return true;
		}
		bool RunModule()
		{
			while (true)
			{
				Util::FileUtil back_dir(_back_dir);
				std::vector<std::string> arr;
				back_dir.ScanDirectory(&arr);
				for (const auto& n : arr)
				{
					if (NeedUpLoad(n) == false)
					{
						continue;
					}
					if (Upload(n) == true)
					{
						_data->Insert(n, GetFileIdentify(n));
					}
				}
				Sleep(1);
			}

		}
	};
}